/**
 * Notes: 定时任务控制器 - 处理定时任务相关的API请求
 * Date: 2025-01-27
 */

const BaseController = require('./base_controller.js');
const SchedulerService = require('../service/scheduler_service.js');

class SchedulerController extends BaseController {

	/**
	 * 执行过期订单和设备状态检查任务
	 * 这个接口应该被定时任务系统调用
	 */
	async processExpiredOrdersAndDevices() {
		console.log('定时任务：处理过期订单和设备状态');
		
		const service = new SchedulerService();
		return await service.processExpiredOrdersAndDevices();
	}

	/**
	 * 检查设备MQTT连接状态
	 */
	async checkDeviceConnections() {
		console.log('定时任务：检查设备连接状态');
		
		const service = new SchedulerService();
		return await service.checkDeviceConnections();
	}

	/**
	 * 清理过期未支付订单
	 */
	async cleanupUnpaidOrders() {
		console.log('定时任务：清理过期未支付订单');
		
		const service = new SchedulerService();
		return await service.cleanupUnpaidOrders();
	}

	/**
	 * 执行所有定时任务（综合接口）
	 */
	async runAllScheduledTasks() {
		console.log('执行所有定时任务...');
		
		const service = new SchedulerService();
		const results = {};

		try {
			// 1. 处理过期订单和设备状态
			results.expiredOrdersAndDevices = await service.processExpiredOrdersAndDevices();

			// 2. 检查设备连接
			results.deviceConnections = await service.checkDeviceConnections();

			// 3. 清理过期未支付订单
			results.unpaidOrders = await service.cleanupUnpaidOrders();

			return {
				success: true,
				message: '所有定时任务执行完成',
				results: results
			};

		} catch (error) {
			console.error('定时任务执行失败:', error);
			return {
				success: false,
				message: '定时任务执行失败',
				error: error.message,
				results: results
			};
		}
	}

}

module.exports = SchedulerController;